const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database()
const _ = db.command

function logs(result) {
	return db.collection('crontab').add({
		data: {
			create_time: new Date,
			result: result,
			identifier: 'drawing'
		}
	})
}
exports.main = async (event, context) => {
	const wxContext = cloud.getWXContext()
	let n_daily = 1,
		n_timeline = 5; //每次更新的daily数量
		let results = []

	while (n_daily > 0) {
		n_daily--;
		//获取一条符合条件的daily
		let date = new Date()
		console.log('当前时间', date)
		let daily = await db.collection('daily')
			.field({
				_id: true,
			})
			.where({
				type: 1,
				time_result: _.lte(date),
				result_status: false
			})
			.orderBy('time_result', 'asc')
			.limit(1)
			.get()
		if (daily.data.length == 0) {
			return logs({
				msg: 'notFoundDaily'
			})
		}
		console.log('获取的daily', daily)

		for (let i = 0; i < n_timeline; i++) {
			let time_begin = (new Date).getTime()
			let result = {}
			let timeline = await db.collection('timeline').field({
				_id: true,
				nums_max: true
			}).where({
				daily_id: daily.data[0]._id,
				result_status: 1
			}).limit(n_timeline).limit(1).orderBy('time_begin', 'asc').get()
			if (timeline.data.length == 0) {
				//更新daily
				let res = await db.collection('daily').doc(daily.data[0]._id).update({
					data: {
						result_status: true
					}
				})
				return logs({
					msg: 'dailyUpdateSuccess',
					res: res
				})
			}
			timeline = timeline.data[0]
			//标记timeline为2，以确保不会被其他任务读取
			await db.collection('timeline').doc(timeline._id).update({
				data: {
					result_status: 2
				}
			})
			result.timeline = timeline
			//获取第n+1条数据
			let theData = await db.collection('appoint').where({
				timeline_id: timeline._id
			}).skip(parseInt(timeline.nums_max)).limit(1).field({
				randkey: true
			}).orderBy('randkey', 'asc').get()
			result.theData = theData
			if (theData.data.length == 0) {
				//预约人次少于最大值，所有人预约成功
				result.update = await db.collection('appoint').where({
					timeline_id: timeline._id
				}).update({
					data: {
						status: 2
					}
				})
			} else {
				//预约成功
				result.update = await db.collection('appoint').where({
					timeline_id: timeline._id,
					randkey: _.lt(theData.data[0].randkey)
				}).update({
					data: {
						status: 2
					}
				})
				//预约失败
				result.update = await db.collection('appoint').where({
					timeline_id: timeline._id,
					status: 1
				}).update({
					data: {
						status: 3
					}
				})
			}
			await db.collection('timeline').doc(timeline._id).update({
				data: {
					result_status: 3
				}
			})
			let time_end = (new Date).getTime()
			result.run = time_end - time_begin
			//保存到结果
			results.push(result)
		}
		

	}
	return logs({
		msg: 'updating',
		results: results
	})
}